<template>
	<!-- <view class="uni-container">
    <uni-forms ref="form" :model="formData" validate-trigger="submit" err-show-type="toast">
      <uni-forms-item name="evaluate_image1" label="评价图片">
        <uni-easyinput placeholder="评价图片" v-model="formData.evaluate_image1"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="evaluate_text" label="评价文字">
        <uni-easyinput placeholder="评价文字" v-model="formData.evaluate_text"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="evaluate_score" label="评价分数">
        <uni-easyinput placeholder="评价分数" type="number" v-model="formData.evaluate_score"></uni-easyinput>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" @click="submit">提交</button>
      </view>
    </uni-forms>
  </view> -->
	<view class="wrap">
		<!-- <u-navbar :custom-back="back" title="评价商品">
  	</u-navbar> -->
		<unicloud-db ref="udb" v-slot:default="{data, pagination, loading, hasMore, error}" collection="t_shop_order"
			:where="where" field="consignee_address,create_time,order_sn,id_address,total_price">
			<view v-if="error">{{error.message}}</view>
			<view v-else-if="data">
				<view class="order_detail">
					<view class="content">
						<view class="title">
							{{'收货地址: ' + order.address}}<br>{{'订单编号: ' + order.order_sn}}<br>{{'创建时间: ' + order.create_time }}
						</view>
						<view class="list">
							<view class="item" v-for="(item,index) in goods" :key="index">
								<u-row gutter="16">
									<u-col :span="3">
										<u-image width="100%" height="150rpx" :src="'https://zhy-demo.oss-cn-hangzhou.aliyuncs.com/upload/'+item.pic"></u-image>
									</u-col>
									<u-col :span="9" @click="toGoods(item.id_goods)">
										<view class="gl-name">{{item.name}}</view>
										<view class="gl-descript">{{item.descript}}</view>
										<!-- <view class="gl-name">红米k20</view>
										<view class="gl-descript">购买流程测试专用商品</view> -->
										<view class="gl-price">
											<u-row>

												<u-col offset="6" :span="3" text-align="right">
													￥{{formatPrice(item.price)}}
												</u-col>
												<u-col :span="3" text-align="right">
													x{{item.count}}
												</u-col>
											</u-row>
										</view>

									</u-col>
								</u-row>
							</view>
						</view>
						<view class="total" v-if="order.coupon_price===undefined" style="color: red;">
							优惠{{order.coupon_discount}}折</view>
						<view class="total" v-else style="color: red;">优惠{{order.coupon_price}}元</view>
						<view class="total">合计: {{formatPrice(order.real_price)}}</view>
					</view>
					<view class="beizhu">
						<image src="../../static/remark.png" mode=""></image>
						<view style="line-height: 60px;font-size: 20px;">
							您的购物满意度？
						</view>
						<view style="line-height: 60px; padding-top: 19px;margin-right: 10px;">
							<u-button size="mini" type="info" style=""
								@click="openPage('/pages/goods/kefu')">
								客服</u-button> 
						</view>
						<view style="line-height: 60px;padding-top: 19px;"> 
							<u-button size="mini" type="info" style="" @click="submit"> 提交</u-button> 
						</view>
					</view>
					<view class="dafen">
						<starsRating :starsIndex="starsIndex" :starsObject="clicked_list" :isEditStars="true"
							@starsClick="starsClick">
						</starsRating> 
					</view>
					<!-- sadasdas -->
					<view>
						<view style="height: auto;">
							<!-- <textarea :value="" maxlength="140" placeholder="请填写您的评价(最多140字)" class="text" v-model="text" /> -->
							<input class="text" v-model="text" type="text" placeholder="    请填写您的评价(最多140字)" />
						</view>
						<view class="example-body box" style="margin-top: 6px;">
							<button class="button " @click="uploadImg" style="background-color: #e1f3d8; color: #fff;">
								<u-icon name="camera" size="25" style="color: #09bb07; margin-right: 10px;"></u-icon> 
								<text class="button-text success-text" style="color: #09bb07;">上传图片</text>
							</button> 
							<button class="button popup-warn" @click="viewImg" style="background-color: #faecd8; color: #fff;">
								<u-icon name="eye" size="25" style="color: #e6a23c;margin-right: 10px;"></u-icon> 
								<text class="button-text warn-text" style="color:#e6a23c;">放大图片</text>
							</button> 
						</view>
						<view >
							<uni-popup ref="share" type="share" safeArea backgroundColor="#fff" >
								<view style="padding: 10px;align-items: center;display: flex;justify-content: center;">
									<uni-section title="预览图片" type="line" >
										<view style="height: 200px;width: 200px;background-repeat: no-repeat;">
											<image :src="getImg()" mode="" style="height: 200px;width: 200px;background-repeat: no-repeat;"></image>
											<!-- <text >222</text> -->
										</view> 
									</uni-section>
								</view>
							</uni-popup>
							<!-- <view  style="align-items:center;height: 50px;width: 50px;" @click="uploadImg">
								<view >
									<u-icon name="camera" size="50" style="color: #ccccd6;"></u-icon> <br>
								</view>
							</view> -->
							<view class="button"  style="height: 150px ;margin: 0 10px;">
								<view v-if="pic1==''">
									<text style="color: #ccccd6;">图片还未上传哦~</text>
								</view> 
								<u-image :src="pic1" alt="" width="120px" height="120px" v-if="pic1!=''"></u-image>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- <uni-load-more :status="loading?'loading':(hasMore ? 'more' : 'noMore')"></uni-load-more> -->
		</unicloud-db>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/t_shop_orderevaluate.js';
	import starsRating from "../../components/StarsRating.vue"
	const db = uniCloud.database();
	const dbCollectionName = 't_shop_orderevaluate';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.indexOf(key) > -1) {
				result[key] = validator[key]
			}
		}
		return result
	}

	let pic = ''

	export default {
		components: {
			starsRating
		},
		computed: { 
		},
		data() {
			let formData = {
				"evaluate_image1": "",
				"evaluate_text": "",
				"evaluate_score": null
			}
			return {
				formData,
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				},
				imgUrl: this.baseApi + '/file/getImgStream?idFile=',
				order: {
					_id : '',
					order_sn: '',
					create_time: '',
					address: '',
					coupon_discount: '',
					coupon_price:'',
				},
				goods:[],
				disabled: false,
				header: {
					Authorization: ''
				},
				action: '',
				pic1: '',
				pic2: '',
				pic3: '',
				text: '',
				starsIndex: 5, // 默认星级评价分数
				clicked_list: {}, //星级评价图标数组 
				where: '',
				orderAllInfo: {},
				uid: '',
				myaddress:'',
			}
		},
		// onLoad(option) {
		// 	this.order.orderSn = option.orderSn
		// 	this.getData()
		// 	this.header.Authorization = this.vuex_token;
		// 	this.action = this.baseApi + '/pages/orderRemark/add';
		// 	var _this = this
		// 	_this.curShowStars(_this.starsIndex)
		// },
		onLoad() {
			this.order.orderSn = '213434'
			// this.order.orderSn = option.orderSn
			// console.log(this.pic1=='')
			// this.pic1=''
			this.uid = uniCloud.getCurrentUserInfo().uid  
			this.where = { 
				order_sn:this.order.orderSn
			} 
			this.getData()
			// this.header.Authorization = this.vuex_token;
			// this.action = this.baseApi + '/pages/orderRemark/add';
			var _this = this
			_this.curShowStars(_this.starsIndex)
		},
		onReady() {
			// this.$refs.form.setRules(this.rules)
		},
		mounted(){
		   this.getImg();
		   this.timer = setInterval(() => {
		       this.pic1 = this.getImg()
			   // console.log(this.pic1)
		   }, 1000)
		},
		methods: {
			updateOrder(orderSn){
				console.log(orderSn)
				db.collection('t_shop_order').where({
					'order_sn':orderSn
				}).update({
					'status':8
				}).then((res) => {
				  // uni.showToast({
				  //   icon: 'none',
				  //   title: '修改成功'
				  // })
				  this.getOpenerEventChannel().emit('refreshData')
				  setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
				  uni.showModal({
				    content: err.message || '请求服务失败',
				    showCancel: false
				  })
				})
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				}) 
				// console.log(uid)
				let timestamp = Date.now()
				let now = new Date(timestamp).toLocaleString() 
				// console.log(now)
				let uid = uniCloud.getCurrentUserInfo().uid  
				// console.log(uid)
				// String a = w.getFullYear()+'-'
				let formData1 = {
				  "create_time": timestamp,
				  "modify_time": timestamp,
				  "evaluate_image1": this.pic1,
				  "evaluate_text": this.text,
				  "evaluate_score": this.starsIndex,
				  "order_sn":this.order.orderSn,
				  "users_id": uid,  
				} 
				  return this.submitForm(formData1) 
				  uni.hideLoading()  
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				console.log(value)
				return db.collection('t_shop_orderevaluate').add(value).then((res) => {
					uni.showToast({
						icon: 'none',
						title: '评论成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					this.updateOrder(value.order_sn)
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},
			back() {
				this.$u.route({
					type: 'navigateBack',
					delta: 1
				})
			},
			async getData() {
				let res = await db.collection('t_shop_order')
				.where({
					order_sn:this.order.orderSn
				}) 
				.get() 
				// console.log(res.result.data)
				this.order.order_sn = res.result.data[0].order_sn
				this.order.create_time = new Date(res.result.data[0].create_time).toLocaleString('chinese', { hour12: false })
					let id_address= res.result.data[0].id_address
					let res1 = await db.collection('t_shop_address').where({_id:id_address}).get()
					let addressCode =  res1.result.data[0].address
					let address_detial =  res1.result.data[0].address_detial
				this.getAddress(addressCode,address_detial) 
					let coupon_id= res.result.data[0].coupon_id
				this.getCouponUserInfo(coupon_id)
				this.order.real_price = res.result.data[0].real_price
					let order_Id = res.result.data[0]._id
				this.getGoodsInfo(order_Id)
				console.log(address)
			},
			getImg(){
				// this.$set(this.pic1,)
				return pic
			},
			viewImg(){ 
				console.log(pic)
				this.$refs.share.open()
				// console.log(222)
				// console.log(this.pic2)
				// this.$set(this.pic1[0], "url", this.pic2);
			},
			uploadImg(){
				uni.chooseImage({
				count: 1,
				success(res) {
					// console.log(res);
					if (res.tempFilePaths.length > 0) {
						uni.showLoading({
							title: '上传中...'
						})
						let filePath = res.tempFilePaths[0]
						let imageUrl = '' 
						uniCloud.uploadFile({
							filePath: filePath,  //要上传的文件对象
							cloudPath: Date.now() + '.jpg',  //保存在云端的文件名，这里以时间戳命名
							success(res) { 
								imageUrl = res.fileID  //云端返回的图片地址 
								this.pic1 = imageUrl 
								pic = imageUrl 
								console.log(pic)  
								let value = {
								  "url": imageUrl, 
								} 
								db.collection('uploadImg').add(value).then((res) => {
									uni.showToast({
										icon: 'none',
										title: '上传成功'
									}) 
								}).catch((err) => {
									uni.showModal({
										content: err.message || '请求服务失败',
										showCancel: false
									})
								}) 
							},
							fail(err) {
								console.log(err)
							},
							complete() {           
								uni.hideLoading() 
							}
						});		
					}
				}
				});  
			},
			getGoodDetail(i){
				console.log(i)
				let id = this.goods[i].id_goods 
				console.log(id) 
				db.collection('t_shop_goods').where({_id:id})
				.get().then((res)=>{  
					// console.log(res.result.data[0].name) 
					this.goods[i].name = res.result.data[0].name
					this.goods[i].descript = res.result.data[0].descript 
					this.goods[i].pic = res.result.data[0].pic 
				}).catch((err) => {
					console.log("error")
				}) 
			},
			getGoodsInfo(id){
				console.log(id)
				let allGoods = []
				db.collection('t_shop_order_item').where({id_order:id})
				.get().then((rs)=>{ 
					allGoods = rs.result.data
					this.goods = allGoods 
					// this.order.coupon_price = rs.result.data[0].coupon_price 
					// console.log(this.order.coupon_discount)
					console.log(allGoods)
					for(let i = 0; i < allGoods.length; i++  ){
						this.getGoodDetail(i) 
					}
				}).catch((err) => {
						console.log("error")
				}) 
			},
			getCouponInfo(id){
				console.log(id)
				db.collection('t_shop_coupon').where({_id:id})
				.get().then((rs)=>{ 
					this.order.coupon_discount = rs.result.data[0].coupon_discount
					this.order.coupon_price = rs.result.data[0].coupon_price 
					// console.log(this.order.coupon_discount)
					// console.log(this.order.coupon_price)
				}).catch((err) => {
						console.log(111)
				}) 
			},
			getCouponUserInfo(id){ 
				console.log(id)
				let coupon_id = ''
				db.collection('t_shop_coupon_user').where({_id:id})
				.get().then((res)=>{
					coupon_id = res.result.data[0].coupon_id   
					this.getCouponInfo(coupon_id)
				})  
				// return rs
			},
			getAddress(code,detail) {
				console.log(code,detail)
				//拼装查询条件  
				let query = '\"code==' + '\'' + code + '\'' + '\"'
				// let myaddress = ''
				// console.log(query)  
				db.collection('opendb-city-china')
					.get({
						getTreePath: {
							"startWith": query //查询具体code所对应的省市区  
						}
					})
					.then((res) => {
						const resdata = res.result.data
						this.order.address = resdata[0].name + resdata[0].children[0].name + resdata[0].children[0]
							.children[0].name + detail
						console.log(this.order.address)
					})
					.catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})
				// this.address = '湖南湘潭市岳塘区'
				// console.log(myaddress)
				return this.myaddress
			},
			formatPrice(price) {
				return (price / 100).toFixed(2);
			},
			toGoods(id) {
				this.$router.push({
					path: '/goods/' + id
				})
			},
			payment() {
				this.$u.route({
					url: '/pages/order/payment/payment',
					params: {
						orderSn: this.order.orderSn,
						totalPrice: this.order.totalPrice
					}
				})
			},
			openPage(url) {
				this.$u.route({
					url: url
				})
			},
			confirmReceive() {
				this.$u.post('user/order/confirm/' + this.order.orderSn).then(res => {
					this.order = res
				})
			},
			contact() {
				this.$u.toast('敬请期待')
			},
			uploadSuccess(data) {
				const avatar = this.baseApi + '/file/getImgStream?idFile=' + data.data.realFileName;
				console.log(data);
				// this.$u.vuex('vuex_avatar', avatar);
				this.pic = avatar;
				this.pic1 = avatar;
				this.pic2 = data.data.realFileName;
				this.disabled = true;
			},
			uploadError() {
				this.$u.toast('上传头像失败');
			},
			submit2() {
				let text = this.text;
				console.log(text);
				if (this.pic1 == '' || this.text == '') {
					this.$u.toast('所填信息不完整');
					return;
				}
				this.$u.post('/user/order/submit/' + this.order.orderSn + '/' + text + '/' + this.pic2 + '/' + this
					.starsIndex).then(res => {
					this.$u.toast('评价成功');
					this.$u.route({
						// type: 'switchTab',
						url: '/pages/user/profile'
					});
					this.$u.post('user/order/endRemark/' + this.order.orderSn).then(res => {
						console.log('完成评价', this.order.orderSn)
						this.$u.route({
							url: '/pages/shop/index'
						})
					});
				}).catch(res => {
					console.log("err", res);
					this.$u.toast(res.msg);
				})
			},
			//打星
			setStar: function(star) {
				starsIndexthis.star = star;
			},
			starsClick: function(starsNum) {
				var _this = this
				_this.starsIndex = starsNum
				console.log(starsNum)
				_this.curShowStars(starsNum)
			},
			// 星星评价展示
			curShowStars: function(starsNum) {
				var _this = this
				if (starsNum == 1) {
					_this.clicked_list = [
						"../../static/star.png", "../../static/nostar.png",
						"../../static/nostar.png", "../../static/nostar.png",
						"../../static/nostar.png"
					]
				} else if (starsNum == 2) {
					_this.clicked_list = [
						"../../static/star.png", "../../static/star.png",
						"../../static/nostar.png", "../../static/nostar.png",
						"../../static/nostar.png"
					]
				} else if (starsNum == 3) {
					_this.clicked_list = [
						"../../static/star.png", "../../static/star.png",
						"../../static/star.png", "../../static/nostar.png",
						"../../static/nostar.png"
					]
				} else if (starsNum == 4) {
					_this.clicked_list = [
						"../../static/star.png", "../../static/star.png",
						"../../static/star.png", "../../static/star.png",
						"../../static/nostar.png"
					]
				} else if (starsNum == 5) {
					_this.clicked_list = [
						"../../static/star.png", "../../static/star.png",
						"../../static/star.png", "../../static/star.png",
						"../../static/star.png"
					]
				} else {
					_this.clicked_list = [
						"../../static/nostar.png", "../../static/nostar.png",
						"../../static/nostar.png", "../../static/nostar.png",
						"../../static/nostar.png"
					]
					_this.starsIndex = 0
				}
				console.log(_this.clicked_list)
			},
		}
	}
</script>

<style>
	.uni-container {
		padding: 15px;
	}

	.uni-input-border,
	.uni-textarea-border {
		width: 100%;
		font-size: 14px;
		color: #666;
		border: 1px #e5e5e5 solid;
		border-radius: 5px;
		box-sizing: border-box;
	}

	.uni-input-border {
		padding: 0 10px;
		height: 35px;

	}

	.uni-textarea-border {
		padding: 10px;
		height: 80px;
	}

	.uni-button-group {
		margin-top: 50px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
	}

	.uni-button {
		width: 184px;
	}
</style>

<style lang="scss" scoped>
	@mixin flex {
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			flex-direction: row;
		}
	
		@mixin height {
			/* #ifndef APP-NVUE */
			height: 100%;
			/* #endif */
			/* #ifdef APP-NVUE */
			flex: 1;
			/* #endif */
		}
	
		.box {
			@include flex;
		}
	
		.button {
			@include flex;
			align-items: center;
			justify-content: center;
			flex: 1;
			height: 35px;
			margin: 0 5px;
			border-radius: 5px;
		}
		
	.dafen {
		display: flex;
		flex-direction: column;
		// align-items: center;
		margin-left: 50px;
		margin-bottom: 10px;
		width: 100%;
		height: 30px;
		background-color: #FFFFFF;
	}

	.order_detail {
		margin: 30rpx;

		.top {
			.address_detail {
				padding: 5px;
			}

			.footer_btn {
				text-align: right;

				.u-btn {
					margin-left: 20rpx;
				}
			}
		}

		.content {
			margin-top: 40rpx;

			.total {
				text-align: right;
				padding: 10px;
			}

			.list {
				.item {
					margin-top: 20rpx;

					.gl-name {
						font-size: 26rpx;
					}

					.gl-descript {
						margin-top: 14rpx;
						font-size: 20rpx;
					}

					.gl-price {
						margin-top: 26rpx;
						font-size: 24rpx;
					}
				}
			}

			.total {}
		}

		.beizhu {
			display: flex;

			// margin-top: 20rpx;
			image {
				vertical-align: middle;
				width: 50px;
				height: 45px;
				margin-right: 15rpx;
				margin-top: 10rpx;
			}

			textarea {
				font-size: 25rpx;
				height: 300px;
				line-height: 50px;
				color: #999;
			}
		}

		.text {
			height: 50px;
			width: 100%;
			background-color: #ededed;
		}

	}
</style>
